<?php
/**
 * 验证码生成器，生成一个包含四个验证字符的图片
 *
 * @package iDaren/dr-includes
 * @author hutushen222 2010-11-1x
 */

# 确认开启session，然后将生成的验证码字符序列将存储在session中
if (!isset($_SESSION)) {
	session_start();
	header('Cache-control: private');
}

# 设置验证码的字符的长度
$captchalen = 4;
# 设置验证码载体图像的宽与高
$width = 65;
$height = 20;

# 生成一个65x20的图像
$image = imagecreate($width, $height);

# 填充背景色
$bg_color = imagecolorallocate($image, 0x33, 0x66, 0xFF);
imagefilledrectangle($image, 0, 0, $width, $height, $bg_color);

# 生成随机字符序列
$text = random_text($captchalen, true);

# 根据字符的数量确定字符在图像中显示的位置
$font = 5;
$x = imagesx($image) / 2 - strlen($text) * imagefontwidth($font) / 2;
$y = imagesy($image) / 2 - imagefontheight($font) / 2;

# 将字符串绘制到图像中
$fg_color = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
imagestring($image, $font, $x, $y, $text, $fg_color);

# 将生成的CAPTCHA字符存储到session中
$_SESSION['captcha'] = $text;

# 输出图像到浏览器中
header('Content-type: image/png');
imagepng($image);

# 释放与图像关联的内存
imagedestroy($image);


/**
 * 随机字符序列生成器
 * 生成指定长度的随机字符序列
 *
 * @param int $count 字符序列的长度
 * @param boolean $rm_similar 是否屏蔽外观相似的字符的在字符序列出现
 */
function random_text($count, $rm_similar = false)
{

	# 创建一个包含字母和数字的字符序列
	$chars = array_flip(array_merge(range(0, 9), range('A', 'Z')));

	// remove similar looking characters that might cause confusion
	if ($rm_similar) {
		unset($chars[0], $chars[1], $chars[2], $chars[5], $chars[8],
		$chars['B'], $chars['I'], $chars['O'], $chars['Q'],
		$chars['S'], $chars['U'], $chars['V'], $chars['Z']);
	}

	// generate the string of random text
	for ($i = 0, $text = ''; $i < $count; $i++) {
		$text .= array_rand($chars);
	}

	return $text;
}

?>